package com.xxwy.ddu.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.xxwy.ddu.common.util.DateUtil;
import com.xxwy.ddu.common.util.WebUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.NamedThreadLocal;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author xxwy
 * on 2018/8/13 0013
 */
public class LogInterceptor implements HandlerInterceptor {

    private NamedThreadLocal<Long> startTimeThreadLocal=new NamedThreadLocal<Long>("StartTime-EndTime");

    private static final Logger logger = LoggerFactory.getLogger(LogInterceptor.class);


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        LogRequestWrapper logRequestWrapper = new LogRequestWrapper(request);
        String parames = WebUtil.getParameters(request,logRequestWrapper.getBody());
        logger.info("servletPath===>{},method==>{} ,parameters====>{}",request.getServletPath(),request.getMethod(),parames);
        startTimeThreadLocal.set(System.currentTimeMillis());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        final Long startTime = startTimeThreadLocal.get();
        final Long endTime = System.currentTimeMillis();
        try {
            HandlerMethod hand = (HandlerMethod) handler;
            logger.info("methodPath====> {}, used time==> {}", hand.getMethod(), DateUtil.parseSs(endTime - startTime));
        } catch (Exception e) {
        }
    }
}
